package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WmNewFeign;
import com.usian.admin.service.AdChannelService;
import com.usian.admin.service.AdSensitiveService;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.GreenImageScan;
import com.usian.common.aliyun.GreenTextScan;
import com.usian.common.fastdfs.FastDFSClientUtil;
import com.usian.common.util.SensitiveWordUtil;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.admin.pojos.AdSensitive;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmUser;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Log4j2
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WmNewFeign wmNewFeign;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private AdSensitiveService adSensitiveService;
    @Autowired
    private AdChannelService adChannelService;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Value("${fileServerUrl}")
    private String fileServerUrl;
    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;



    @Override
    @GlobalTransactional
    public boolean autoScanByMediaNewsId(Integer id) {
        boolean flag =false;
        try {

            //1:根据文章id获取文章详情
            if(id == null){
                log.info("审核文章id为空");
                return flag;
            }
            WmNews wmNews = wmNewFeign.findWmNewsFeignById(id);
            if(wmNews ==null){
                log.info("根据文章id查询获取文章为空");
                return flag;
            }
            //2:校验审核状态。不同状态走不同流程 人工审核 3  已审核 8  return
            if(wmNews.getStatus()==4){
                saveAppArticle(wmNews); //人工审核成功
                flag = true;
                return flag;
            }
            //getTime 15787474283182   157323435232433
            if(wmNews.getStatus()==8 && wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
                this.updateWmNews(wmNews,(short) 9,"审核通过已发布");
                saveAppArticle(wmNews); //审核通过待发布
                flag = true;
                return flag;
            }

            //3:待审核逻辑  调用阿里云内容检测  敏感词   更新wmnews 审核状态
            if(wmNews.getStatus()==1){
                //提取文章中的文本和图片
                Map<String, Object> result = this.handleTextAndImages(wmNews);

                //调阿里云内容检测
                Map map = greenTextScan.greeTextScan(result.get("content").toString());
                if (!map.get("suggestion").equals("pass")){
                    if(map.get("suggestion").equals("block")){
                        //失败  更新状态  审核失败 2
                        this.updateWmNews(wmNews,(short) 2,"阿里云文本审核失败");
                        return flag;
                    }

                    if(map.get("suggestion").equals("review")){
                        //审核不确定  更新状态  交给人工审核 3
                        this.updateWmNews(wmNews,(short) 3,"阿里云文本审核不确定，提交人工审核");
                        return flag;
                    }
                }

                //审核图片
                List<String> images = (List<String>)result.get("images");
                List<byte[]> imageList = new ArrayList<>();
                // fileServerUrl  过滤图片字段
                for (String image : images) {
                    //htttp://192.168.58.138/group1/M00....png
                    //group1/M00....png
                    String imageName = image.replace(fileServerUrl, "");
                    int index = imageName.indexOf("/");
                    String groupName = imageName.substring(0, index);
                    String imagePath = imageName.substring(index + 1);
                    byte[] imageByte = fastDFSClientUtil.download(groupName, imagePath);
                    imageList.add(imageByte);
                }

                Map imageMap = greenImageScan.imageScan(imageList);
                if (!imageMap.get("suggestion").equals("pass")){
                    if(imageMap.get("suggestion").equals("block")){
                        //失败  更新状态  审核失败 2
                        this.updateWmNews(wmNews,(short) 2,"阿里云图片审核失败");
                        return flag;
                    }

                    if(imageMap.get("suggestion").equals("review")){
                        //审核不确定  更新状态  交给人工审核 3
                        this.updateWmNews(wmNews,(short) 3,"阿里云图片审核不确定，提交人工审核");
                        return flag;
                    }
                }


                //3:敏感词审核
                List<AdSensitive> allSensitive = adSensitiveService.findAllSensitive();
                List<String> list = new ArrayList<>();
                for(AdSensitive a :allSensitive){
                    list.add(a.getSensitives());
                }
                SensitiveWordUtil.initMap(list);
                Map<String, Integer> content = SensitiveWordUtil.matchWords(result.get("content").toString());
                if(content.size()>0){
                    //失败  更新状态  审核失败 2
                    this.updateWmNews(wmNews,(short) 2,"敏感词库审核失败");
                    return flag;
                }

                //4:判断审核状态  如果审核通过 且 发布时间>当前时间  8审核通过待发布  发布时间<=当前时间  9 审核通过已发布
                if(wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
                    this.updateWmNews(wmNews,(short) 8,"审核通过待发布");
                }else{
                    this.updateWmNews(wmNews,(short) 9,"审核通过已发布");



                    //引入es，单条插入数据
                }

                //5:保存一系列的文章表
                flag =true;
                saveAppArticle(wmNews);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    private void updateWmNews(WmNews wmNews, short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wmNewFeign.updateWmNews(wmNews);
    }


    public Map<String,Object> handleTextAndImages(WmNews wmNews){
        String content="";
        //存储纯文本内容
        StringBuilder sb = new StringBuilder();
        //存储图片
        List<String> images = new ArrayList<>();

        if(wmNews!=null){
            content = wmNews.getContent();
        }

        List<Map> contentList = JSONArray.parseArray(content,Map.class);
        for(Map map :contentList){
            if (map.get("type").equals("text")) {
                sb.append(map.get("value"));
            }

            if (map.get("type").equals("image")) {
                images.add((String) map.get("value"));
            }
        }

        if(wmNews.getImages()!=null && wmNews.getType()!=0){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String, Object> reslutMap = new HashMap<>();
        reslutMap.put("content",sb.toString());
        reslutMap.put("images",images);
        return reslutMap;
    }

    //保存发布文章的三张表  ap_article/ap_article_content/ap_article_config
    public void  saveAppArticle(WmNews wmNews){

        //1：保存主表
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());
        apArticle.setPublishTime(wmNews.getPublishTime());
        //1.1根据自媒体用户的id 查询作者信息
        WmUser wmUser = wmNewFeign.findByUserId((long)wmNews.getUserId());
        if(wmUser!=null){
            ApAuthor apAuthor = articleFeign.selectAuthorByName(wmUser.getName());
            if(apAuthor!=null){
                apArticle.setAuthorId((long)apAuthor.getId());
                apArticle.setAuthorName(apAuthor.getName());
            }
        }

        //1.2维护频道信息
        Integer channelId = wmNews.getChannelId();
        AdChannel adChannel = adChannelService.getById(channelId);
        if(adChannel!=null){
            apArticle.setChannelId(channelId);
            apArticle.setChannelName(adChannel.getName());
        }
        //1.3 保存
        ApArticle article = articleFeign.saveArticle(apArticle);

        //保存第二个 ap_article_content
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(article.getId());
        apArticleContent.setContent(wmNews.getContent());
        articleFeign.saveArticleContent(apArticleContent);

        //保存第三个 ap_article_config
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(article.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsComment(true);
        articleFeign.saveArticleConfig(apArticleConfig);
    }

}
